﻿using Diamond.OrderContext.Domain.Exceptions;
using Diamond.OrderContext.ACL.Ports.Clients;
using Diamond.OrderContext.ACL.Ports.Repositories;
using System.Threading.Tasks;

namespace Diamond.OrderContext.Domain
{
    public class OrderService : IOrderService
    {
        private readonly IOrderRepository _orderRepository;
        private readonly IInventoryClient _inventoryClient;

        public OrderService(IOrderRepository orderRepository, IInventoryClient inventoryClient)
        {
            _orderRepository = orderRepository;
            _inventoryClient = inventoryClient;
        }

        public async Task PlaceOrder(Order order)
        {
            if (order.IsValid())
            {
                throw new InvalidOrderException();
            }

            var inventoryReview = await _inventoryClient.Check(order);

            if (!inventoryReview.IsAvaliable())
            {
                throw new NotEnoughInventoryException();
            }

            _orderRepository.Add(order);
            await _inventoryClient.Lock(order);
        }
    }
}
